package org.superheroes.androidclient.net.discovery;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.superheroes.androidclient.gui.Filmpje;

import android.util.Log;

/**
 * 
 * @author Jeffrey Goudzwaard
 * @author Davin Terrizzi
 * @version 1.0
 *
 */
public class DiscoveryFinder
{

	private final String	webServerIp	= "10.0.2.2";
	private URL				discoveryUrl;

	public DiscoveryFinder()
	{

	}

	public void init() throws MalformedURLException
	{
		discoveryUrl = new URL( "http://" + webServerIp + "/websites/mm_discovery/discovery_select.php" );

	}

	public ArrayList<Filmpje> fillEntries() throws Exception
	{
		HttpURLConnection connection = ( HttpURLConnection ) discoveryUrl.openConnection();
		String result = "";

		StringBuilder sb = new StringBuilder();
		sb.append( "status=" );
		sb.append( "get_available" );

		//String data = sb.toString();

		try
		{
			connection.setDoInput( true );
			connection.setDoOutput( true );
			connection.setUseCaches( false );
			connection.setRequestMethod( "GET" );

			// Read result
			BufferedReader in = null;
			try
			{
				String line;
				in = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );
				while ( ( line = in.readLine() ) != null )
				{
					result += line;
				}

				return getFromJson( result );

			}
			finally
			{
				if ( in != null )
				{
					in.close();
				}
			}

		}
		finally
		{
			connection.disconnect();
			Log.i( "Resultaat: ", result );
		}

	}

	/**
	 * Loads the videos from JSON
	 * @param poep
	 * @return
	 * @throws Exception
	 */
	public static ArrayList<Filmpje> getFromJson( String poep ) throws Exception
	{
		ArrayList<Filmpje> filmpjes = new ArrayList<Filmpje>();

		JSONArray array = ( JSONArray ) new JSONTokener( poep ).nextValue();

		for ( int i = 0; i < array.length(); i++ )
		{
			JSONObject ding1 = ( JSONObject ) array.get( i );

			Filmpje f = new Filmpje( ding1.getString( "machine" ), ding1.getString( "filename" ) );
			filmpjes.add( f );
		}

		return filmpjes;

	}

}
